<script lang="ts" setup>
import { reactive } from "vue";
import { ScriptTemplateSelect } from "@/components/business";
import api from "@/api";
import type { ScriptResultDTO, SseEvent } from "@/types";
import { YesIcon, NoIcon } from "@/components/icons";

interface State {
  visible: boolean;
  templateId: string;
  machineIds: string[];
  scriptResultList: ScriptResultDTO[];
}

const state = reactive<State>({
  visible: false,
  templateId: "",
  machineIds: [],
  scriptResultList: []
});

const submit = () => {
  state.scriptResultList = [];
  api.scriptTemplate.execScriptTemplate(
    {
      id: state.templateId,
      machineIds: state.machineIds
    },
    (event: SseEvent) => {
      console.log(event);
      state.scriptResultList.push(JSON.parse(event.data));
    }
  );
};

const openDialog = (ids: string[]) => {
  state.visible = true;
  state.machineIds = ids;
  state.scriptResultList = [];
};

const closeDialog = () => {
  state.visible = false;
};

defineExpose({
  openDialog,
  closeDialog
});
</script>
<template>
  <el-dialog v-model="state.visible" title="选择脚本模板" :close-on-click-modal="false">
    <div h-500px flex flex-col>
      <div>
        <script-template-select v-model:value="state.templateId" />
      </div>
      <div>执行结果:</div>
      <div flex-1 overflow-y-scroll>
        <div
          flex
          items-center
          v-for="item in state.scriptResultList"
          :key="item.message"
          style="white-space: pre-wrap"
        >
          {{ item.message }}
          <YesIcon w-30px h-30px v-if="item.success" />
          <NoIcon w-30px h-30px v-else />
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="state.visible = false">取消</el-button>
        <el-button type="primary" @click="submit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
